﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using AttributeRouting;
using AttributeRouting.Web.Mvc;
using LuxDiner.Logic.Products;
using LuxDiner.Model.Products;
namespace LuxDiner.Web.Management.Areas.Products.Controllers
{
    [RouteArea("Products")]
    [RoutePrefix("Product")]
    [Authorize(Roles = "Admin,ProductManage")]
    public class ProductController : Controller
    {
        [Route("")]
        public ActionResult Index()
        {
            return View();
        }

        [Route("Edit/{id:int?}")]
        public ActionResult Edit(int id = 0)
        {
            var categories = ProductCategoryLogic.GetCategories(null);
            ViewBag.Categories = categories;
            ProductModel model;
            if (id > 0)
                model = ProductLogic.GetModel(id);
            else
                model = new ProductModel();
            return PartialView(model);
        }

        [Route("Export")]
        public ActionResult Export()
        {
            try
            {
                ProductQuery sea = new ProductQuery();
                sea.Key = Request.Form.Get("key");
                sea.Categories = Request.Form.Get("categorys");
                var lst = ProductLogic.GetProducts(sea);
                if (lst.Count > 0)
                {
                    Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(Server.MapPath("/RootFiles/Templates/Exports/product.xls"));
                    var cells = workbook.Worksheets[0].Cells;
                    for (var i=0;i<lst.Count;i++)
                    {
                        var pro = lst[i];
                        cells[i + 1, 0].Value = pro.ProductNo;
                        cells[i + 1, 1].Value = pro.ProductName;
                        cells[i + 1, 2].Value = pro.Pinyin;
                        cells[i + 1, 3].Value = pro.UnitName;
                        cells[i + 1, 4].Value = pro.AssistantUnitName;
                        cells[i + 1, 5].Value = pro.AssistantUnitRate;

                    }
                    var buffer = workbook.SaveToStream().ToArray();
                    return File(buffer, "application/octet-stream", "产品列表.xls");
                }
                else
                    return Content("暂无数据");
            }
            catch (Exception ex)
            {
                Common.Logger.Error("", ex);
                return Content("服务器运行出错，请联系开发商。");
            }
        }
    }
}
